package com.yoxio.scanservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yoxio.scanservice.redis.RedisComponent;
import com.yoxio.scanservice.service.ScanService;
import com.yoxio.scanservice.utils.ShaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author pht
 * @date 2021/10/22 15:39
 */
@Service
public class ScanServiceImpl implements ScanService {

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 中间页地址,这里我是部署在了uniCloud上
     */
    private static final String SCAN_HTML_URL = "https://static-4c846183-0572-4bb6-abf9-784372f0f965.bspapp.com?token=";

    private static final Long QR_CODE_EXPIRE_TIME = 5 * 60L;


    /**
     * 扫码状态,可封装枚举
     * 未扫码
     */
    private static final int QR_CODE_STATUS_WAIT = 1;
    /**
     * 已扫码
     */
    private static final int QR_CODE_STATUS_SCAN = 2;
    /**
     * 已登录
     */
    private static final int QR_CODE_STATUS_SUCCESS = 3;
    /**
     * 已失败
     */
    private static final int QR_CODE_STATUS_FAIL = 4;

    /**
     * 超时
     */
    private static final int QR_CODE_STATUS_EXPIRE = 5;

    /**
     * 获取二维码内容
     *
     * @return
     */
    @Override
    public JSONObject getScanParam() {
        //生成token
        String s = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase() + System.currentTimeMillis();
        String token = ShaUtil.sha1(s);
        //生成内容
        String content = SCAN_HTML_URL + token;
        redisComponent.set(token, QR_CODE_STATUS_WAIT, QR_CODE_EXPIRE_TIME);

        JSONObject object = new JSONObject();
        object.put("token", token);
        object.put("content", content);
        object.put("expireTime", QR_CODE_EXPIRE_TIME);
        return object;
    }

    /**
     * 获取二维码状态
     *
     * @param token
     * @return
     */
    @Override
    public JSONObject getQrcodeStatus(String token) {

        JSONObject object = new JSONObject();
        //redis获取
        String s = redisComponent.get(token);
        if (StringUtils.isEmpty(s)) {
            s = QR_CODE_STATUS_EXPIRE + "";
        }
        object.put("status", s);
        return object;
    }
}
